/************************************************************************
* content_meshgen.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"
#include "content.h"
#include "array.h"

#include "graphics.h"

#include <stdarg.h>

static void content_meshgen_add_texture(contentfeatures_t *f, uint32_t pos, char* img)
{
	material_t *mat;

	mat = array_get_ptr(&f->materials,(pos&0xFF0));
	if (!mat) {
		mat = mat_from_image("texture",img);
		if (!mat)
			return;
		mat_options(mat,f->materials_info);
		array_set_ptr(&f->materials,mat,(pos&0xFF0));
	vlprintf(CN_INFO,"mat: '%s' '%s' %d %d %d",img,mat->name,(pos&0xFF0),f->materials.length,mat->textures.length);
		return;
	}

	mat_add_image(mat,"texture",img);
	vlprintf(CN_INFO," mat: '%s' '%s' %d %d %d",img,mat->name,(pos&0xFF0),f->materials.length,mat->textures.length);
}

static void content_meshgen_add_colour(contentfeatures_t *f, uint32_t pos, colour_t *c)
{
	material_t *mat;

	mat = array_get_ptr(&f->materials,(pos&0xFF0));
	if (!mat) {
		mat = mat_from_colour(c);
		if (!mat)
			return;
		mat_options(mat,f->materials_info);
		array_set_ptr(&f->materials,mat,(pos&0xFF0));
		return;
	}

	mat_add_colour(mat,c);
}

/* generate the materials for a content item */
void content_meshgen_textures(contentfeatures_t *f, ...)
{
	char* img;
	colour_t c;
	uint32_t type;
	uint32_t pos;
	va_list ap;

	va_start(ap,f);

	while ((type = va_arg(ap,uint32_t)) != CMD_NONE) {
		pos = va_arg(ap,uint32_t);
		switch (type) {
		case CMD_TEXTURE:
			img = va_arg(ap,char*);
			content_meshgen_add_texture(f,pos,img);
			break;
		case CMD_COLOUR:
			c.r = va_arg(ap,uint32_t);
			c.g = va_arg(ap,uint32_t);
			c.b = va_arg(ap,uint32_t);
			c.a = va_arg(ap,uint32_t);
			content_meshgen_add_colour(f,pos,&c);
			break;
		default:
			vlprintf(CN_ERROR,"Unknown material type '%u' for content 0x%.4X",type,f->content);
			return;
		}
	}

	va_end(ap);
}
